package com.ruoyi;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.config.DeepSeekConfig;
import com.ruoyi.medol.Message;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import com.alibaba.fastjson2.JSON;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;

import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeoutException;

@SpringBootTest
@Slf4j
public class test {
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static String API_KEY = "sk-ebdf9950bd9c406aa3dbc8abd9db0a8d";
    private final OkHttpClient client = new OkHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void sendChatRequest( ) {
        // 1. 构建请求体
        Message message = new Message();
        message.setRole("user");
        message.setContent("你好");

        ChatRequest requestBody = new ChatRequest();
        requestBody.setModel("deepseek-chat");
        requestBody.setMessages(Collections.singletonList(message));

        String jsonBody = JSON.toJSONString(requestBody);

        // 2. 创建 HTTP 请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();


                    Flux.<String>create(sink -> {
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            String errorMsg = "请求失败: " + e.getMessage();
                            log.error(errorMsg);
                            sink.error(new RuntimeException(errorMsg));
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            try (ResponseBody body = response.body()) {
                                if (!response.isSuccessful()) {
                                    String errorMsg = "HTTP错误: " + response.code() + " - " + response.message();
                                    log.error(errorMsg);
                                    sink.error(new RuntimeException(errorMsg));
                                    return;
                                }

                                if (body == null) {
                                    String errorMsg = "响应体为空";
                                    log.error(errorMsg);
                                    sink.error(new RuntimeException(errorMsg));
                                    return;
                                }

                                log.debug("开始接收流式响应...");


                                    String line = body.string();


                                        System.out.println("原始响应行: "+line);

                                        try {
                                            JsonNode rootNode = objectMapper.readTree(line);
                                            if (rootNode.has("choices")) {
                                                JsonNode choices = rootNode.get("choices");
                                                if (choices.isArray() && choices.size() > 0) {
                                                    JsonNode firstChoice = choices.get(0);
                                                    if (firstChoice.has("delta") && firstChoice.get("delta").has("content")) {
                                                        String content = firstChoice.get("delta").get("content").asText();
                                                        if (content != null && !content.isEmpty()) {
                                                            log.debug("解析到内容: {}", content);
                                                            sink.next(content);
                                                            // 实时输出到控制台
                                                            System.out.print(content);
                                                            System.out.flush(); // 确保立即输出
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (JsonProcessingException e) {
                                            log.warn("JSON解析失败: {}", line, e);
                                        }

                                    sink.complete();

                            } catch (Exception e) {
                                log.error("处理响应时发生异常", e);
                                sink.error(e);
                            }
                        }
                    });
                })
                .doOnSubscribe(sub -> log.info("开始订阅流"))
                .doOnComplete(() -> System.out.println("\n[对话结束]"))
                .doOnError(e -> System.err.println("\n[发生错误: " + e.getMessage() + "]"))
                .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))
                        .doBeforeRetry(retry -> log.warn("第 {} 次重试...", retry.totalRetries() + 1))
                        .onRetryExhaustedThrow((spec, signal) -> {
                            log.error("重试次数耗尽，最后错误: {}", signal.failure().getMessage());
                            return new RuntimeException("服务暂时不可用，请稍后重试");
                        }))
                .onErrorResume(e -> {
                    log.error("最终错误处理", e);
                    return Flux.just("[服务错误: " + e.getMessage() + "]");
                });
    }
    @Test
    public void demoUsage() throws IOException {
        sendChatRequest("你好").subscribe(
                chunk -> System.out.print(chunk), // 每次收到数据
                error -> System.err.println("出错"), // 错误处理
                () -> System.out.println("\n流结束") // 完成回调
        );
    }

    public Flux<String> teste() throws IOException {
        Flux<String> flux = null;

        Message message =new Message();
        message.setRole("user");
        message.setContent("你好");
        ChatRequest requestBody = new ChatRequest();
        requestBody.setModel("deepseek-chat");
        requestBody.setMessages(Collections.singletonList(message));


        String jsonBody = JSON.toJSONString(requestBody);
        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " - " + response.message());
            }

            if (response.body() == null) {
                throw new IOException("响应体为空");
            }

            String responseBody = response.body().string();
            System.out.println("原始响应: " + responseBody); // 打印原始响应，检查格式

            // 检查是否是流式响应（如 "[DONE]" 或 SSE 格式）
            if (responseBody.trim().equals("[DONE]")) {
                System.out.println("流式响应结束");
                return null;
            }

            // 尝试解析 JSON
            try {
                // 假设返回类似 OpenAI 的格式：
                // {"choices":[{"message":{"content":"Hello!"}}]}
                // 或流式格式：{"choices":[{"delta":{"content":"Hi"}}]}
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(responseBody);

                if (rootNode.has("choices")) {
                    JsonNode choices = rootNode.get("choices");
                    if (choices.isArray() && choices.size() > 0) {
                        JsonNode firstChoice = choices.get(0);
                        if (firstChoice.has("message") && firstChoice.get("message").has("content")) {
                            String content = firstChoice.get("message").get("content").asText();
                            System.out.println("AI 回复: " + content);
                            flux = Flux.just(content);
                        } else if (firstChoice.has("delta") && firstChoice.get("delta").has("content")) {
                            String content = firstChoice.get("delta").get("content").asText();
                            System.out.println("AI 流式回复: " + content);
                        } else {
                            System.out.println("无法解析 choices 结构: " + firstChoice);
                        }
                    }
                } else if (rootNode.has("error")) {
                    String errorMsg = rootNode.get("error").get("message").asText();
                    throw new IOException("API 返回错误: " + errorMsg);
                } else {
                    System.out.println("未知响应格式: " + responseBody);
                }
            } catch (JsonProcessingException e) {
                throw new IOException("JSON 解析失败: " + e.getMessage() + "\n原始响应: " + responseBody);
            }
        }
        return flux;
    }
    public Flux<String> sendChatRequest(String question) {
        ChatRequest request = new ChatRequest();
        Message userMessage = new Message();
        userMessage.setRole("user");
        userMessage.setContent(question);
        request.setMessages(Collections.singletonList(userMessage));



        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

        Flux<String> flix = null;
        String jsonBody = JSON.toJSONString(request);
        Request okRequest = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                .header("Authorization", "Bearer sk-ebdf9950bd9c406aa3dbc8abd9db0a8d")
                .header("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(okRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " - " + response.message());
            }

            if (response.body() == null) {
                throw new IOException("响应体为空");
            }

            String responseBody = response.body().string();
            System.out.println("原始响应: " + responseBody); // 打印原始响应，检查格式

            // 检查是否是流式响应（如 "[DONE]" 或 SSE 格式）
            if (responseBody.trim().equals("[DONE]")) {
                System.out.println("流式响应结束");
                return null;
            }

            // 尝试解析 JSON
            try {
                // 假设返回类似 OpenAI 的格式：
                // {"choices":[{"message":{"content":"Hello!"}}]}
                // 或流式格式：{"choices":[{"delta":{"content":"Hi"}}]}
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(responseBody);

                if (rootNode.has("choices")) {
                    JsonNode choices = rootNode.get("choices");
                    if (choices.isArray() && choices.size() > 0) {
                        JsonNode firstChoice = choices.get(0);
                        if (firstChoice.has("message") && firstChoice.get("message").has("content")) {
                            String content = firstChoice.get("message").get("content").asText();
                            System.out.println("AI 回复: " + content);
                            flix = Flux.just(content);
                        } else if (firstChoice.has("delta") && firstChoice.get("delta").has("content")) {
                            String content = firstChoice.get("delta").get("content").asText();
                            System.out.println("AI 流式回复: " + content);
                        } else {
                            System.out.println("无法解析 choices 结构: " + firstChoice);
                        }
                    }
                } else if (rootNode.has("error")) {
                    String errorMsg = rootNode.get("error").get("message").asText();
                    throw new IOException("API 返回错误: " + errorMsg);
                } else {
                    System.out.println("未知响应格式: " + responseBody);
                }
            } catch (JsonProcessingException e) {
                throw new IOException("JSON 解析失败: " + e.getMessage() + "\n原始响应: " + responseBody);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return flix;

    }
}
